const Controller = require('egg').Controller
const fs = require('fs');
const path = require('path');
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');

class UserInfo extends Controller {
    async index() {
        const { ctx } = this
        await ctx.render('userInfo.html', {
            message: ''
        })
    }

    async avatar() {
        const { ctx } = this

        const stream = await ctx.getFileStream();

        const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();

        const target = path.join(this.config.baseDir, 'app/public/uploads', filename);

        const writeStream = fs.createWriteStream(target);

        try {
            //异步把文件流 写入
            await awaitWriteStream(stream.pipe(writeStream));
        } catch (err) {
            //如果出现错误，关闭管道
            await sendToWormhole(stream);
            throw err;
        }

        let upImage = '/public/uploads/' + filename

        //console.log(upImage)

        ctx.body = {
            url: upImage
        }
    }

    async upload() {
        const { ctx } = this

        let query = ctx.request.body
        //console.log(query)

        const setText = await ctx.service.userInfo.find()

        if (!setText) {
            await ctx.render('userInfo.html', {
                message: '添加个人信息失败'
            })
        } else {
            const getResult = await ctx.service.userInfo.update(query, setText)
            if (getResult) {
                ctx.body = {
                    err_code: 0,
                    message: 'OK'
                }
            }
        }
    }
}

module.exports = UserInfo